<template>
  <view class="police-home-container bg-white min-h-[100vh]">
    <view class="head px-2 box-border">
      <!-- 用户信息 -->
      <view class="user flex flex-row justify-between items-center py-4">
        <userOfTopLeft
          :userAvatar="userInfoStore.userInfo.avatar"
          :userName="userInfoStore.userInfo.userName"
          showStatusTag
          :statusTagName="userInfo.dutyStatus == 3 ? '不在岗' : '在岗'"
          @onUserInfo="onPageJump('/subPages/police/mine/index')"
        ></userOfTopLeft>
        <view class="relative">
          <image
            class="w-[33rpx] h-[33rpx]"
            src="http://cy.meta-links.com.cn/icon/pull-down.png"
            @click="showStatusList = !showStatusList"
          />
          <view
            :class="
              showStatusList
                ? 'status-list open w-[140rpx] text-[#0189FE] text-[25rpx] text-center absolute top-[50rpx] right-0 z-10'
                : 'status-list w-[140rpx] text-[#0189FE] text-[25rpx] text-center absolute top-[50rpx] right-0 z-10'
            "
          >
            <template v-if="userInfo.dutyStatus != 3">
              <view
                class="bg-white h-[42rpx] rounded-3.5 px-2.25 mb-1.75 leading-[42rpx]"
                @click="
                  showModal1 = true;
                  showStatusList = false;
                "
                >状态设置</view
              >
              <view
                class="bg-white h-[42rpx] rounded-3.5 px-2.25 mb-1.75 leading-[42rpx]"
                @click="
                  showModal2 = true;
                  showStatusList = false;
                "
                >下班</view
              >
            </template>
            <view
              class="bg-white h-[42rpx] rounded-3.5 px-2.25 leading-[42rpx]"
              @click="fileReport"
              >报备</view
            >
          </view>
        </view>
      </view>

      <!-- 轮播图 -->
      <view class="swiper">
        <up-swiper
          :list="swipers"
          circular
          @change="(e: any) => (current = e.current)"
          height="360rpx"
          radius="16rpx"
        >
          <template #indicator>
            <view class="indicator">
              <view
                class="indicator__dot"
                v-for="(item, index) in swipers"
                :key="index"
                :class="[index === current && 'indicator__dot--active']"
              >
              </view>
            </view>
          </template>
        </up-swiper>
      </view>
    </view>
    <view class="content px-4 box-border">
      <view class="mt-2.5">
        <menuWithBg :menuList="menuList" @onMenuItem="onMenu"></menuWithBg>
      </view>
      <view class="list-menu w-[100%] h-[125rpx] rounded-8.75 mt-6 relative">
        <image
          class="w-[100%] h-[100%]"
          src="http://cy.meta-links.com.cn/icon/jzcmBg.png"
        ></image>
        <view
          class="w-[100%] h-[100%] absolute top-0 left-0 z-5 flex flex-row items-center"
        >
          <view class="icon-box">
            <image
              src="http://cy.meta-links.com.cn/icon/alarm.png"
              mode="aspectFit"
            ></image>
          </view>
          <text class="text-black text-[31rpx] tracking-[5rpx] ml-3"
            >警钟长鸣</text
          >
          <button
            class="btn-489DFB btn-mini mr-3"
            @click="onPageJump('/subPages/police/alarmRing/index')"
          >
            进入专区
          </button>
        </view>
      </view>
    </view>
    <view class="custom-modal">
      <up-modal
        :show="showModal1"
        title="在岗状态设置"
        :closeOnClickOverlay="true"
        showCancelButton
        confirmColor="#ffffff"
        cancelColor="#000000"
        @confirm="editStatus(selectStatus)"
        @cancel="showModal1 = false"
        @close="showModal1 = false"
      >
        <template #default>
          <view
            class="flex flex-row justify-between items-center text-[33rpx] pt-[68rpx] w-[100%]"
          >
            <view
              :class="
                selectStatus == 2
                  ? 'active w-[194rpx] h-[83rpx] text-center leading-[83rpx]'
                  : 'unactive w-[194rpx] h-[83rpx] text-center leading-[83rpx]'
              "
              @click="selectStatus = 2"
              >巡逻</view
            >
            <view
              :class="
                selectStatus == 1
                  ? 'active w-[194rpx] h-[83rpx] text-center leading-[83rpx]'
                  : 'unactive w-[194rpx] h-[83rpx] text-center leading-[83rpx]'
              "
              @click="selectStatus = 1"
              >外出</view
            >
          </view>
        </template>
      </up-modal>
    </view>
    <view class="custom-modal">
      <up-modal
        :show="showModal2"
        title="提示"
        content="确认下班后状态将变为【不在岗】？"
        contentTextAlign="center"
        :closeOnClickOverlay="true"
        showCancelButton
        confirmColor="#ffffff"
        cancelColor="#000000"
        @confirm="editStatus(3)"
        @cancel="showModal2 = false"
        @close="showModal2 = false"
      ></up-modal>
    </view>
    <!-- 消息订阅弹窗 -->
    <u-modal
      :show="showSubMsgPopup"
      title="消息订阅"
      content="是否允许订阅办事咨询和工作任务的微信服务消息推送功能？"
      showCancelButton
      @cancel="closeSubMsgPop()"
      @confirm="
        showSubMsgPopup = false;
        subscribeMsg();
      "
    ></u-modal>
    <up-toast ref="uToastRef"></up-toast>
  </view>
</template>

<script setup lang="ts">
import menuWithBg from "@/components/menuWithBg/menuWithBg.vue";
import {
  getNoReadCount,
  setPoliceStatus,
  getPoliceClockTip,
  snapshotunreadNums
} from "@/api/police/index";
import { policeClockAdd } from "@/api/police/clock";
import { policeUserInfo } from "@/api/user";
import { communityById } from "@/api/community/index";
import { qqmapKey } from "@/config/app";
import { onPageJump } from "@/utils/tools";
import QQMapWX from "@/common/qqmap-wx-jssdk.js";
import { useUserInfoStore } from "@/stores/userInfo";
const userInfoStore = useUserInfoStore();

const current = ref(0);
const data = reactive({
  userInfo: <any>{},
  selectStatus: <any>null, //0 在岗 1在岗-外出 2 在岗巡逻 3 不在岗(下班)
  showStatusList: false,
  showModal1: false,
  showModal2: false,
  showSubMsgPopup: false,
});
const {
  userInfo,
  selectStatus,
  showStatusList,
  showModal1,
  showModal2,
  showSubMsgPopup,
} = toRefs(data);

const uToastRef = <any>ref(null);
const swipers = reactive([
  "https://mscy.cqlandun.com:8088/static/police-banner1.png",
  "https://mscy.cqlandun.com:8088/static/police-banner2.png",
  "https://mscy.cqlandun.com:8088/static/police-banner3.png",
]);
// 菜单
const menuList = ref([
  {
    title: "社区工作扫码打卡",
    bgColor: "darkGreen",
    badge: 0,
  },
  {
    title: "每月工作提示",
    bgColor: "purple",
    badge: 0,
  },
  {
    title: "办事咨询提示",
    bgColor: "yellow",
    badge: 0,
  },
  {
    title: "群众评价",
    bgColor: "tangerine",
    badge: 0,
  },
  {
    title: "群众投诉",
    bgColor: "azure",
    badge: 0,
  },
  {
    title: "线上清廉",
    bgColor: "xsql",
    badge: 0,
  },
  {
    title: "隐患随手拍",
    bgColor: "yhsp",
    badge: 0,
  },
]);
// 菜单项点击操作
const onMenu = (item: any) => {
  if (item.title === "社区工作扫码打卡") {
    policeClock();
  }
  if (item.title === "每月工作提示") {
    uni.navigateTo({
      url: "/subPages/police/workReminder/workReminder",
    });
  }
  if (item.title === "办事咨询提示") {
    uni.navigateTo({
      url: "/subPages/police/serviceConsultation/index",
    });
  }
  if (item.title === "群众评价") {
    uni.navigateTo({
      url: "/subPages/police/mobEvaluation/mobEvaluationTip",
    });
  }
  if (item.title === "群众投诉") {
    uni.navigateTo({
      url: "/subPages/police/mobComplaint/mobComplaintTip",
    });
  }
  if (item.title === "线上清廉") {
    uni.navigateTo({
      url: "/subPages/police/honesty/index",
    });
  }
  if (item.title === "隐患随手拍") {
    // uni.navigateTo({
    //   url: "/subPages/police/honesty/index",
    // });
    uni.navigateTo({
      url: `/subPages/crowd/news/zsssp?newsTitle=隐患随手拍`,
    });
  }
};
// 报备
const fileReport = () => {
  showStatusList.value = false;
  uni.navigateTo({
    url: "/subPages/police/report/fileReport",
  });
};
// 获取各类消息未读数量
const onNoReadStat = () => {
  uni.showLoading({
    title: "加载中",
    mask: true,
  });
  getNoReadCount({})
    .then((res) => {
      uni.hideLoading();
      const { data } = res;
      menuList.value[1].badge = +data.taskCount;
      menuList.value[2].badge = +data.consultCount;
    })
    .catch((err) => {
      uni.hideLoading();
      uToastRef.value.show({
        type: "error",
        message: err,
      });
    });
};
// wduxxx   vvs
const wduxxx = () => {
  uni.showLoading({
    title: "加载中",
    mask: true,
  });
  snapshotunreadNums({})
    .then((res) => {
      uni.hideLoading();
      const { data } = res;
      menuList.value[6].badge = +data.unRead;
    })
    .catch((err) => {
      uni.hideLoading();
      uToastRef.value.show({
        type: "error",
        message: err,
      });
    });
};
// 获取个人信息
const getUserInfo = () => {
  policeUserInfo({ policeUserId: userInfoStore.userInfo.userId })
    .then((res) => {
      const { data } = res;
      userInfo.value = data;
      selectStatus.value = data.dutyStatus;
    })
    .catch((err) => {
      uToastRef.value.show({
        type: "error",
        message: err,
      });
    });
};
// 状态设置
const editStatus = (status: number) => {
  if (status === userInfo.value.dutyStatus) {
    if (status === 3) {
      uni.showToast({
        title: "已是下班状态",
        icon: "none",
        mask: true,
      });
      showModal2.value = false;
    } else {
      uni.showToast({
        title: "请选择状态",
        icon: "none",
        mask: true,
      });
    }
  } else {
    setPoliceStatus({ dutyStatus: status })
      .then((_res) => {
        status === 3 ? (showModal2.value = false) : (showModal1.value = false);
        uToastRef.value.show({
          type: "success",
          message: "状态设置成功",
        });
        getUserInfo();
      })
      .catch((err) => {
        if (status === 3) {
          showModal2.value = false;
        } else {
          showModal1.value = false;
          selectStatus.value === userInfo.value.dutyStatus;
        }
        uToastRef.value.show({
          type: "error",
          message: err,
        });
      });
  }
};
// 扫码打卡
const policeClock = () => {
  // 实例化腾讯API核心类
  let qqmapsdk = new QQMapWX({ key: qqmapKey });
  uni.scanCode({
    onlyFromCamera: true,
    success: function (res) {
      if (res.result) {
        let communityId = res.result.substring(res.result.indexOf("=") + 1);
        communityById(Number(communityId))
          .then((res1) => {
            const { data } = res1;
            if (data.id != userInfo.value.communityId) {
              uToastRef.value.show({
                type: "error",
                message: "请扫描您所属社区二维码！",
              });
            } else {
              if (data.lat && data.lnt && data.clockInRange) {
                uni.getLocation({
                  type: "gcj02",
                  success: function (res) {
                    // 计算两点之间的直线距离（单位为米）
                    const distance = calculateDistance(
                      res.latitude,
                      res.longitude,
                      data.lat,
                      data.lnt
                    );
                    // console.log(
                    //   "当前位置的经纬度：----" + res.latitude,
                    //   res.longitude
                    // );
                    // console.log("距离是" + distance + "公里"); // 输出：3934.85（单位：公里）
                    // console.log(
                    //   "打卡范围是" +
                    //     (Number(data.clockInRange) / 1000).toFixed(5) +
                    //     "公里"
                    // );
                    if (
                      Number(distance) <=
                      Number((Number(data.clockInRange) / 1000).toFixed(5))
                    ) {
                      console.log("成功");
                      qqmapsdk.reverseGeocoder({
                        location: {
                          latitude: res.latitude,
                          longitude: res.longitude,
                        },
                        success: function (result: any) {
                          // console.log(result.result.address); // 输出解析结果
                          policeClockAdd({
                            policeUserId: userInfoStore.userInfo.userId,
                            clockAddress: result.result.address,
                          })
                            .then(async (res2: any) => {
                              if (res2.code === 200) {
                                uni.navigateTo({
                                  url: "/subPages/police/clock/clockTip?status=1",
                                });
                              }
                            })
                            .catch((err: any) => {
                              uToastRef.value.show({
                                type: "error",
                                message: err,
                              });
                            });
                        },
                        fail: function (error: any) {
                          console.log(error); // 输出错误信息
                          uToastRef.value.show({
                            type: "error",
                            message: error.message,
                          });
                        },
                      });
                    } else {
                      console.log("失败");
                      uni.navigateTo({
                        url: "/subPages/police/clock/clockTip?status=0",
                      });
                    }
                  },
                  fail: function (_err) {
                    uToastRef.value.show({
                      type: "error",
                      message: "当前位置信息获取失败",
                    });
                  },
                });
              } else {
                uToastRef.value.show({
                  type: "error",
                  message: "请核实社区位置或打卡范围！",
                });
              }
            }
          })
          .catch((err) => {
            uToastRef.value.show({
              type: "error",
              message: err,
            });
          });
      } else {
        uToastRef.value.show({
          type: "error",
          message: "请扫码社区打卡二维码",
        });
      }
    },
  });
};
// 计算距离
const calculateDistance = (
  lat1: number,
  lon1: number,
  lat2: number,
  lon2: number
) => {
  let R = 6378.137; // 地球半径（单位：千米）
  let radLat1 = (lat1 * Math.PI) / 180.0; //lat1 * Math.PI / 180.0=>弧度计算
  let radLat2 = (lat2 * Math.PI) / 180.0;
  let a = radLat1 - radLat2;
  let b = (lon1 * Math.PI) / 180.0 - (lon2 * Math.PI) / 180.0;
  let s =
    2 *
    Math.asin(
      Math.sqrt(
        Math.pow(Math.sin(a / 2), 2) +
          Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)
      )
    );
  s = s * R;
  s = Math.round(s * 10000) / 10000; // 输出为公里
  return Number(s).toFixed(5);
};
// 获取民警打卡提示信息
const policeClockTipInfo = () => {
  getPoliceClockTip({ policeUserId: userInfoStore.userInfo.userId })
    .then((res) => {
      const { data } = res;
      // 0 不提示 1 昨日打卡缺卡一次 2 昨日打卡缺卡两次
      if (data.punchPrompt && data.punchPrompt != 0) {
        uToastRef.value.show({
          type: "info",
          message: data.punchPromptName,
        });
      }
    })
    .catch((err) => {
      uToastRef.value.show({
        type: "error",
        message: err,
      });
    });
};
// 消息订阅
const subscribeMsg = () => {
  uni.requestSubscribeMessage({
    tmplIds: ["Jyz9Ae3NjjMDhTiNMcm3ygdZypx7ER-7At3JH4zryZo"],
    success(res: any) {
      // 用户同意订阅该模板
      if (res["Jyz9Ae3NjjMDhTiNMcm3ygdZypx7ER-7At3JH4zryZo"] === "accept") {
        console.log("用户同意订阅Jyz9Ae3NjjMDhTiNMcm3ygdZypx7ER");
        uni.setStorageSync("isSubscribeMsg", true);
      } else {
        uni.setStorageSync("isSubscribeMsg", false);
        uToastRef.value.show({
          type: "warning",
          message: "您拒绝了消息订阅，将无法接受消息通知！",
        });
      }
      policeClockTipInfo();
    },
    fail(err) {
      console.error("订阅消息失败", err);
    },
  });
};
const closeSubMsgPop = () => {
  showSubMsgPopup.value = false;
  uni.setStorageSync("isSubscribeMsg", false);
  uToastRef.value.show({
    type: "warning",
    message: "您拒绝了消息订阅，将无法接受消息通知！",
  });
  policeClockTipInfo();
};

// watch(
//   () => showSubMsgPopup.value,
//   (newVal, oldVal) => {
//     // if (!newVal) policeClockTipInfo();
//   }
// );

onLoad(() => {
  if (uni.getStorageSync("isSubscribeMsg")) {
    showSubMsgPopup.value = false;
    policeClockTipInfo();
  } else {
    showSubMsgPopup.value = true;
  }
  getUserInfo();
  // onNoReadStat();
});
onShow(() => {
  uni.hideHomeButton();
  onNoReadStat();
  wduxxx();
});

onShareAppMessage((res) => {
  return {
    title: "码上朝阳",
    path: "/pages/crowd/home/index",
    imageUrl: "/static/logo.png",
    content: "我的码上朝阳小程序",
    mpId: "wxbaec7c3e7b23e9c4",
    type: 0,
  };
});
</script>

<style lang="scss" scoped>
.police-home-container {
  .head {
    background: linear-gradient(180deg, #0088fe 0%, #f4f5f9 100%);
  }

  .user {
    width: 100%;
    .right {
      width: 20%;
    }
  }

  .indicator {
    @include flex(row);
    justify-content: center;

    &__dot {
      height: 14rpx;
      width: 14rpx;
      border-radius: 100px;
      background-color: #eee;
      margin: 0 5px;
      transition: background-color 0.3s;

      &--active {
        background-color: #098cfe;
      }
    }
  }

  .swiper ::v-deep .u-swiper__wrapper__item__wrapper__title {
    background-color: transparent !important;
  }

  .list-menu {
    box-shadow: 0rpx 2rpx 4rpx 1rpx rgba(0, 0, 0, 0.16);
    .icon-box {
      width: 90rpx;
      height: 90rpx;
      background: #fff;
      border: 0.7rpx solid #707070;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: 22rpx;
      > image {
        width: 100%;
        height: 100%;
      }
    }
  }

  .unactive {
    border: 0.7rpx solid #707070;
    color: #000000;
  }

  .active {
    border: 0.7rpx solid #489dfb;
    color: #489dfb;
  }

  .custom-modal {
    ::v-deep .u-modal__title {
      font-size: 33rpx;
      color: #000000;
      padding-top: 40rpx;
    }
    ::v-deep .u-modal__content {
      padding: 92rpx 25px 92rpx 25px;
    }
    ::v-deep .u-modal__content__text {
      font-size: 33rpx;
      color: #000000;
      text-align: center !important;
      padding-top: 68rpx;
    }
    ::v-deep .u-modal__button-group__wrapper--confirm {
      background-color: #489dfb;
    }
    ::v-deep .u-modal__button-group__wrapper__text {
      font-size: 33rpx;
    }
  }

  .status-list {
    opacity: 0;
    transform: scale(0.5); /* 初始缩放比例较小 */
    transition: transform 0.5s ease, opacity 0.5s ease; /* 动画持续时间和缓动函数 */
  }

  .status-list.open {
    opacity: 1;
    transform: scale(1); /* 打开时的缩放比例为正常大小 */
  }
}
</style>
